package com.duanfh;

import com.duanfh.HttpAction.impl.InitRequestImpl;
import com.duanfh.HttpAction.impl.InitResponseImpl;
import com.duanfh.Request.Request;
import com.duanfh.RequestMapping.MyMapping;
import com.duanfh.Response.Response;
import com.duanfh.Servlet.MyServlet;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author duanfh
 */
public class MySocket {
    private static Logger logger = Logger.getLogger(MySocket.class);
    public static void startServer(int port){
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            logger.info("Myserver start as : "+port);
            Socket socket = null;
            while (true){
                socket = serverSocket.accept();
                logger.info("accept ... ");
                //TODO 抽象出方法初始化request和response
                Request request =  new InitRequestImpl().getRequest(socket);
                Response response = new InitResponseImpl().getResponse(socket);
                //TODO 抽象实现逻辑
                String clazz = MyMapping.mapping.get(request.getMyurl());
                logger.info("myUrl is "+clazz);
                if(clazz!=null){
                    Class<MyServlet> aClass = (Class<MyServlet>) Class.forName(clazz);
                    MyServlet myServlet = aClass.newInstance();
                    myServlet.service(request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        startServer(8088);
    }
}
